package org.dromara.job.snailjob;

import cn.hutool.json.JSONObject;
import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.aizuda.snailjob.common.core.util.JsonUtil;
import com.aizuda.snailjob.common.log.SnailJobLog;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.constant.GlobalConstants;
import org.dromara.common.core.enums.FormatsType;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.oce.constant.CommonConstantsJuLang;
import org.dromara.oce.domain.OceAdvertiserReferralRelation;
import org.dromara.oce.mapper.OceAdvertiserReferralRelationMapper;
import org.dromara.oce.service.OcePromotionAddEverydayCensusService;
import org.dromara.oce.utils.TimeUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


/**
 * @author opensnail
 * @date 2024-05-17
 */
@Component
@JobExecutor(name = "promotionAddStatJob")
@RequiredArgsConstructor
public class PromotionAddStatJobExecutor {

    private final OceAdvertiserReferralRelationMapper referralRelationMapper;
    private final OcePromotionAddEverydayCensusService promotionAddEverydayCensusService;

    public ExecuteResult jobExecute(JobArgs jobArgs) throws ParseException {
        SnailJobLog.REMOTE.info("promotionAddStatJob. jobArgs:{}", JsonUtil.toJsonString(jobArgs));
        JSONObject jsonObject = new JSONObject(JsonUtil.toJsonString(jobArgs));
        String jobParamStr = jsonObject.getStr("jobParams");
        Date statDateTemp = DateUtils.addDays(new Date(), -1);
        List<String> params = null;
        //分批处理
        int batchSize; //每批次处理的大小
        if(StringUtils.isNotBlank(jobParamStr)){
            params = Arrays.asList(jobParamStr.split("_"));
        }
        if(CollectionUtils.isNotEmpty(params)){
            batchSize = Integer.parseInt(params.get(0));
            if(params.size() > 1){
                statDateTemp = DateUtils.parseDate(params.get(1), FormatsType.YYYY_MM_DD.getTimeFormat());
            }
        } else {
            batchSize = 200;
        }
        List<String> dateList = new ArrayList<>();
        dateList.add(DateUtils.parseDateToStr(FormatsType.YYYY_MM_DD, statDateTemp));
        LambdaQueryWrapper<OceAdvertiserReferralRelation> lqw = Wrappers.lambdaQuery();
        lqw.eq(OceAdvertiserReferralRelation::getPullStatus, CommonConstantsJuLang.PULL_STATUS_ON);
        List<OceAdvertiserReferralRelation> referralRelations = referralRelationMapper.selectJobList(lqw);
        if (CollectionUtils.isNotEmpty(referralRelations)) {
            // 根据日期拉取每天每小时的消耗数据
            dateList.forEach(date -> {
                SnailJobLog.REMOTE.info("promotionAddStatJob date " + date);
                // 天的时间戳
                Long dateTimestamp = TimeUtils.getTimestampSecond(date);
                for (int i = 0; i < referralRelations.size(); i += batchSize) {
                    int endIndex = Math.min(i + batchSize, referralRelations.size());
                    List<OceAdvertiserReferralRelation> batchList = referralRelations.subList(i, endIndex);
                    promotionAddEverydayCensusService.syncPromotionAddData(batchList,date,dateTimestamp);
                }
                // 删除缓存的投手的广告数据
                String keys = GlobalConstants.GLOBAL_REDIS_KEY + "oce:promotionAddNum:*";
                RedisUtils.deleteKeys(keys);
            });
        }
        return ExecuteResult.success("广告每日新增数量同步执行成功!");
    }
}
